import {
  $digest,
  $init
} from '../../lib/page.data'
import {
  $login,
  $request,
  Session
} from '../../lib/page.auth'

const {
  regeneratorRuntime
} = global
//获取应用实例
let api = require('../../utils/api.js');
let util = require('../../utils/util.js');
let http = require('../../utils/http.js');
/* 引入wxSearch js */
var WxSearch = require('../../wxSearch/wxSearch.js')
var intras;
const app = getApp();

Page({
  data: {
    userInfo: {},
    skill_list: {},
    priceList: {},
    min_host: api.domain,
    opunit: api.opunit,
    user_id: wx.getStorageSync("user_id"),
    longitude: wx.getStorageSync("longitude"),
    latitude: wx.getStorageSync("latitude"),
  },
  //选择技能价格
  toBuyTap: function (e) {
    let id = e.currentTarget.dataset.id;
    // let uid = e.currentTarget.dataset.uid;
    wx.navigateTo({
      url: '/pages/indexBuy/indexBuy?id=' + id
    })
  },
  //获取某一技能更多价格列表
  moreTap: function (e) {
    console.log(e);
    let skill_id = e.currentTarget.dataset.id;
    let skill_name = e.currentTarget.dataset.name;
    let matching = e.currentTarget.dataset.matching;
    console.log(skill_id);
    wx.navigateTo({
      url: '/pages/indexNavipage/indexNavipage?id=' + skill_id + '&name=' + skill_name + '&matching=' + matching,
    })
  },
  buyNow: function (e) {
    var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/indexBuyOrder/indexBuyOrder?pid=' + id,
    })
  },
  onLoad(options) {
    var that = this;
    console.log(wx.getStorageSync("user_id"))
    // 定位
    if (wx.getStorageSync("user_id") == "" || wx.getStorageSync("user_id") == null) {
      // 显示授权登录
      this.authorization = this.selectComponent("#authorization");
      var token = wx.getStorageSync("token");
      console.log(token)
      this.authorization.show();
    } else {
      that.getLonLat();

    }


    wx.setStorageSync("start", 0);
    var openid = options.openid;
    if (openid != '') {
      wx.setStorage({
        key: 'parent_openid',
        data: openid,
      });
    }

    // app.login();

    console.log("我走过了");

    //初始化微信搜索
    //初始化的时候渲染wxSearchdata 第二个为你的search高度
    WxSearch.init(that, 43, []);
    WxSearch.initMindKeys([]);
  },
  /* 微信搜索组件WxSearch相关事件 */
  wxSearchFn: function (e) {
    console.log('搜索关键字为：', e.detail.value);
    var that = this;
    WxSearch.wxSearchAddHisKey(that);
    //跳转至搜索结果页面
    wx.navigateTo({
      url: '/pages/search/search?name=' + e.detail.value
    })
  },
  wxSearchInput: function (e) {
    var that = this;
    WxSearch.wxSearchInput(e, that);
  },
  wxSerchFocus: function (e) {
    var that = this;
    WxSearch.wxSearchFocus(e, that);
  },
  wxSearchBlur: function (e) {
    var that = this;
    WxSearch.wxSearchBlur(e, that);
  },
  wxSearchKeyTap: function (e) {
    var that = this;
    WxSearch.wxSearchKeyTap(e, that);
  },
  wxSearchDeleteKey: function (e) {
    var that = this;
    WxSearch.wxSearchDeleteKey(e, that);
  },
  wxSearchDeleteAll: function (e) {
    var that = this;
    WxSearch.wxSearchDeleteAll(that);
  },
  wxSearchTap: function (e) {
    var that = this;
    WxSearch.wxSearchHiddenPancel(that);
  },

  async getPriceList(user_id) {
    var that = this;
    console.log(that.data.user_id)
    http.get(api.price_list, {
      lat: wx.getStorageSync("latitude"),
      lon: wx.getStorageSync('longitude'),
      user_id: user_id
    }, function (res) {
      console.log(res)
      if (res.data.code == 0) {
        wx.showModal({
          title: "提示",
          content: res.data.info,
          showCancel: false
        });
      } else {
        //刷新
        that.setData({
          priceList: res.data.data
        })

      }
    }, "请求中...");


  },

  async getSkills(user_id) {
    var that = this;
    console.log(api.skill_list);
    http.get(api.skill_list, { user_id: user_id }, function (res) {
      if (res.data.code == 0) {
        wx.showModal({
          title: "提示",
          content: res.data.info,
          showCancel: false,

        });
      } else {
        //刷新
        // that.data.page = 1;
        console.log(res.data.data);
        that.setData({
          skill_list: res.data.data
        })

      }
    }, "请求中...");

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  onMyevent: function (e) {
    var that = this;
    //获取技能列表
    if (that.data.latitude == "" || that.data.latitude == null) {
      that.getLonLat();


    } else {
      that.getSkills(wx.getStorageSync("user_id"));
      that.getPriceList(wx.getStorageSync("user_id"));
    }


  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    console.log("show")
    if (wx.getStorageSync("user_id") == "" || wx.getStorageSync("user_id") == null || wx.getStorageSync("latitude") == "") {
      return false;

    } else {
      that.getPriceList(wx.getStorageSync("user_id"));

    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //获取经纬度并且更新用户经纬度数据
  getLonLat() {
    var token = wx.getStorageSync('token');
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log('系统定位');
        const latitude = res.latitude
        const longitude = res.longitude
        wx.setStorageSync('latitude', latitude);
        wx.setStorageSync('longitude', longitude);
        //clearTimeout(intras);
        console.log(latitude, longitude)
        const speed = res.speed
        const accuracy = res.accuracy
        that.geo(latitude, longitude);
        that.getSkills(wx.getStorageSync("user_id"));
        that.getPriceList(wx.getStorageSync("user_id"));
      },
      fail(res) {
        console.log(res);
        //微信未给小程序授权{"errMsg":"getLocation:fail auth deny"}，或系统未给微信授权{"errMsg":"getLocation:fail system permission denied"}
        console.log('系统定位权限被禁用');

        wx.showModal({
          title: '系统定位权限未开启',
          content: '建议打开位置授权或者查看手机定位权限',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#345391',
          success: function (res) {
            console.log(res)
            if (res.confirm) {
              wx.openSetting({
                success: function (res) {
                  console.log(res)
                  console.log(res.authSetting['scope.userLocation']);
                  that.getLonLat();
                },
                fail: function () {
                  console.log('openSetting.failed')
                  wx.showModal({
                    title: '定位失败',
                    content: '无法使用定位权限，推荐信息失败',
                    confirmText: '太遗憾了',
                    confirmColor: '#345391',
                    showCancel: false
                  })
                }
              })

            }

          }
        });

      },
      complete(res) {
        console.log('complete函数:' + JSON.stringify(res));
      }
    })
  },
  geo: function (latitude, longitude) {
    var token = wx.getStorageSync('token');
    console.log("我走了 geo")
    var that = this;
    wx.request({
      url: 'https://api.map.baidu.com/geocoder/v2/?ak=hQeyEDEFtUc3kGnTNXj97IhuNpGRes0O&location=' + latitude + ',' + longitude + '&output=json',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function (ops) {
        console.log(ops)
        console.log('定位城市：', ops.data.result.formatted_address)
        console.log('定位城市：', ops.data.result.addressComponent.city)
        var data = {
          token: token,
          latitude: latitude,
          longitude: longitude,
          city: ops.data.result.addressComponent.city,
          district: ops.data.result.addressComponent.district,
          province: ops.data.result.addressComponent.province,
          openid: wx.getStorageSync('user_info').openid,
          parent_openid: wx.getStorageSync("parent_openid")
        }
        http.post(api.user_info_set, data, function (res) {
          if (res.data.code == 1) {

          }
        });

      },
      fail: function (resq) {
        var data = {
          token: token,
          latitude: 35.42545,
          longitude: 119.46242,
          city: '日照',
          district: '东港',
          province: '山东',
          parent_openid: wx.getStorageSync("parent_openid")
        }
        http.post(api.user_info_set, data, function (res) {
          if (res.data.code == 1) {

          }
        });
      }

    })
  }
})